package com.manner.groupon.service.other.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.manner.groupon.common.BaseResponse;
import com.manner.groupon.common.ResultUtils;
import com.manner.groupon.exception.CustomException;
import com.manner.groupon.service.other.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author manner
 * @description 针对文件上传操作Service
 * @createDate 2024-10-10 16:28:50
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${file.upload-path}")
    private String uploadPath;

    @Value("${file.prev}")
    private String prev;

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public BaseResponse<String> upload(MultipartFile file) {
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件类型
        String type = FileUtil.extName(fileName);
        //日志输出
        log.info("【上传文件名称为】：{}，【文件类型为】：{}", fileName, type);
        //创建文件上传路径对象
        File uploadFile = new File(uploadPath);
        //判断路径存不存在
        if (!uploadFile.exists()) {
            //不存在,创建
            uploadFile.mkdirs();
        }
        //定义一个文件唯一标识码
        String name = UUID.randomUUID().toString();
        //定义路径
        String path = uploadPath + "/" + name + StrUtil.DOT + type;
        log.info("【最终路径为】：{}", path);
        //创建上传文件对象
        File upload = new File(path);
        //转移文件
        try {
            file.transferTo(upload);
        } catch (IOException e) {
            throw new CustomException("文件上传失败");
        }
        //获取图片访问地址
        String url = prev + "/img/" + name + StrUtil.DOT + type;
        //返回数据
        return ResultUtils.success(url);
    }

    @Override
    public BaseResponse<String> removeFile(String filePath) {
        //截取路径
        int index = filePath.lastIndexOf("/");
        //定义文件名称
        String fileName = "";
        //判断
        if (index != -1) {
            fileName = filePath.substring(index + 1);
        }
        //创建文件上传路径对象
        String delFilePath = uploadPath + fileName;
        //日志输出
        log.info("【要删除的文件路径为】：{}", delFilePath);
        //实例化对象
        File file = new File(delFilePath);
        //判断文件是否存在
        if (file.exists()) {
            //存在,删除
            file.delete();
            //返回数据
            return ResultUtils.success("删除成功");
        }
        //不存在
        return ResultUtils.fail("文件不存在");
    }
}